package com.duobaoyu.dby.supply.admin.listener;

import com.duobaoyu.dby.common.core.service.CacheTemplate;
import com.duobaoyu.dby.supply.admin.service.BalanceChangeInfoService;
import com.duobaoyu.dby.supply.biz.constant.SupplyChainConstants;
import com.duobaoyu.dby.supply.biz.enums.RedisKeys;
import com.duobaoyu.dby.supply.common.biz.dto.account.BalanceInfoDTO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.concurrent.BasicThreadFactory;
import org.jetbrains.annotations.NotNull;
import org.springframework.boot.availability.AvailabilityChangeEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 启动添加timer任务
 *
 * @author fengshaoyu
 * @version 1.0.0
 * @date 2023/9/26 10:14
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class CacheApplicationListener implements ApplicationListener<AvailabilityChangeEvent<?>> {

	private final CacheTemplate<?> cacheTemplate;
	private final BalanceChangeInfoService balanceChangeInfoService;

	@Override
	public void onApplicationEvent(@NotNull AvailabilityChangeEvent event) {
		ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor(1,
				new BasicThreadFactory.Builder().namingPattern(SupplyChainConstants.THREAD_POOL_NAME).daemon(true).build());
		executorService.scheduleAtFixedRate(() -> {
			try {
				cacheTemplate.remove(RedisKeys.CHANNEL_BALANCE_KEY.key());
				//财务缓存刷新
				BalanceInfoDTO balanceInfo = new BalanceInfoDTO();
				balanceInfo.setIfRefresh(Boolean.TRUE);
				balanceChangeInfoService.queryBalanceAndCount(balanceInfo);
				if(log.isDebugEnabled()) {
					log.debug("message:{}", "财务缓存刷新成功");
				}
			} catch (Exception e) {
				log.warn("message:{},data:{}", "财务缓存刷新失败", e);
			}
		},0,30, TimeUnit.MINUTES);
	}
}
